package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.*;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    RedissonClient redissonClient;

    @Override
    @Transactional
    public Result seckillVoucher(Long voucherId) {
//        return oversold(voucherId);
//        return ofo(voucherId);
//        return ofoWithRedislock(voucherId);
//        return ofoWithRedisson(voucherId);
//        return ofoAsync(voucherId);

        return ofoAsyncRedis(voucherId);
    }


    private final static DefaultRedisScript<Long> redisScript;
    static {
        redisScript = new DefaultRedisScript<>();
        redisScript.setLocation(new ClassPathResource("asyncOder.lua"));
        redisScript.setResultType(Long.class);
    }

    private final static DefaultRedisScript<Long> redisScript1;
    static {
        redisScript1 = new DefaultRedisScript<>();
        redisScript1.setLocation(new ClassPathResource("asyncOderReids.lua"));
        redisScript1.setResultType(Long.class);
    }



    /**
     * @Description: 一人一单,AsyncRedis
     * @Param:  * @param voucherId
     * @return: com.hmdp.dto.Result
     * @Author: Feng
     * @Date:2023/03/09 11:01
     */
    private Result ofoAsyncRedis(Long voucherId) {
        //获取代理类
        proxy = (IVoucherOrderService)AopContext.currentProxy();
        Long orderId = idWorker.nextId(SystemConstants.ORDER_VOUCHER_PREFIX);
        //执行lua脚本
        ArrayList<String> keyList = new ArrayList<>();
        keyList.add(voucherId.toString());
        String userId = String.valueOf(UserHolder.getUser().getId());
        Long count = stringRedisTemplate.execute(redisScript1, keyList, userId,orderId.toString());
        //判断
        if(count!=0){
            return count==1? Result.fail("订单不足"):Result.fail("一人一单");
        }


        //返回订单id
        return Result.ok(orderId);
    }

    private static final BlockingQueue<VoucherOrder> BLOCKING_QUEUE = new ArrayBlockingQueue<>(1024*1024);
    private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor();
    private IVoucherOrderService proxy;
    @PostConstruct
//    在项目初始化之后就直接运行
    private void init(){
        //使用java的阻塞队列
//        EXECUTOR_SERVICE.submit(new HandlerVoucherOrderTask());
        //使用stream
//        EXECUTOR_SERVICE.submit(new HandlerVoucherOrderTaskWithRedis());
    }

    private class HandlerVoucherOrderTaskWithRedis implements Runnable{
        @Override
        public void run() {
            String queueName = "stream:orders";
            while (true){
                try {
                    //获取消息
                    //XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STEAMS stream:orders >
                    List<MapRecord<String, Object, Object>> mapRecords = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    //判断是否有消息
                    if (CollectionUtil.isEmpty(mapRecords))
                        continue;
                    //消费
//                    解析数据
                    MapRecord<String, Object, Object> entries = mapRecords.get(0);
                    Map<Object, Object> value = entries.getValue();
//                    用map填充bean
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    handleVoucherOder(voucherOrder);
                    //确认 XACK stream:orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",entries.getId());
                } catch (Exception e) {
                    log.error("处理订单异常｛｝",e);
                    handlerVoucherOrderTaskPreparing();
                }
            }
        }

        private void handlerVoucherOrderTaskPreparing() {

            String queueName = "stream:orders";
            while (true){
                try {
                    //获取消息
                    //XREADGROUP GROUP g1 c1 COUNT 1 STEAMS stream:orders >
                    List<MapRecord<String, Object, Object>> mapRecords = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName,ReadOffset.from("0"))
                    );
                    //判断是否有消息
                    if (CollectionUtil.isEmpty(mapRecords))
                        break;
                    //消费
//                    解析数据
                    MapRecord<String, Object, Object> entries = mapRecords.get(0);
                    Map<Object, Object> value = entries.getValue();
//                    用map填充bean
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    handleVoucherOder(voucherOrder);
                    //确认 XACK stream:orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",entries.getId());
                } catch (Exception e) {
                    log.error("处理订单异常");
                }
            }
        }
    }

    private class HandlerVoucherOrderTask implements Runnable{
        @Override
        public void run() {
            while (true){
                try {
                    VoucherOrder voucherOrder = BLOCKING_QUEUE.take();
                    handleVoucherOder(voucherOrder);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @Description: 一人一单,Async
     * @Param:  * @param voucherId
     * @return: com.hmdp.dto.Result
     * @Author: Feng
     * @Date:2023/03/09 11:01
     */
    private void handleVoucherOder(VoucherOrder voucherOrder) {
        //另一个线程，获取不到ThreadLocal中的值
        Long userId = voucherOrder.getUserId();
        //使用互斥锁解决一人一单d
        //获取互斥锁
        //不加也行，redis中能保证，兜底操作
        RLock lock = redissonClient.getLock("lock:order:"+userId);
        //默认是失败返回，30s后释放
        boolean isLock = lock.tryLock();
        try {
            if(isLock){
//                proxy.createOrder(voucherOrder);
//                老师的这个没有加事务
                createOrder(voucherOrder);
            }
        } finally {
            lock.unlock();
        }
    }

    @Transactional
    //方法执行完事务才算提交
    public void createOrder(VoucherOrder voucherOrder) {
//        从传来的订单中获取userId
        Integer count = query().eq("voucher_id", voucherOrder.getVoucherId()).eq("user_id", voucherOrder.getUserId()).count();
        if(count!=0) return;
        //解决超卖,下单的时候再进行判断
        Boolean upd = seckillVoucherService.update().gt("stock",0).eq("voucher_id",voucherOrder.getVoucherId()).setSql(" stock = stock-1 ").update();
        if(!upd) return;

        //插入订单
        save(voucherOrder);
    }

    /**
     * @Description: 一人一单,Async
     * @Param:  * @param voucherId
     * @return: com.hmdp.dto.Result
     * @Author: Feng
     * @Date:2023/03/09 11:01
     */
    private Result ofoAsync(Long voucherId) {
        //执行lua脚本
        ArrayList<String> keyList = new ArrayList<>();
        keyList.add(voucherId.toString());
        String userId = String.valueOf(UserHolder.getUser().getId());
        Long count = stringRedisTemplate.execute(redisScript, keyList, userId);
        //判断
        if(count!=0){
            return count==1? Result.fail("订单不足"):Result.fail("一人一单");
        }
        //todo 异步执行
        //封装订单，放入阻塞队列
        Long orderId = idWorker.nextId(SystemConstants.ORDER_VOUCHER_PREFIX);
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(Long.parseLong(userId));
        voucherOrder.setVoucherId(voucherId);
        BLOCKING_QUEUE.add(voucherOrder);

        //获取代理类
        proxy = (IVoucherOrderService)AopContext.currentProxy();
        //返回订单id
        return Result.ok(orderId);
    }

    /**
     * @Description: 一人一单,Redisson
     * @Param:  * @param voucherId
     * @return: com.hmdp.dto.Result
     * @Author: Feng
     * @Date:2023/03/09 11:01
     */
    private Result ofoWithRedisson(Long voucherId) {
        //判断优惠券状态
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        if(voucher==null) return Result.fail("该优惠券不存在");
        LocalDateTime now = LocalDateTime.now();
        if (voucher.getBeginTime().isAfter(now)) return Result.fail("优惠券还没开卖");
        if (voucher.getEndTime().isBefore(now)) return Result.fail("优惠券已结束");
        if (voucher.getStock()==0) return Result.fail("优惠券已经卖完");


        //使用互斥锁解决一人一单d
        Long orderId = null;
        Long userId = UserHolder.getUser().getId();
        System.out.println(1);
        //获取互斥锁
        RLock lock = redissonClient.getLock("lock:order:"+userId);
        //默认是失败返回，30s后释放
        boolean isLock = lock.tryLock();
        try {
            if(isLock){
                IVoucherOrderService voucherOrderServiceProxy = (IVoucherOrderService)AopContext.currentProxy();
                orderId = voucherOrderServiceProxy.createOrder(voucherId);
            }
        } finally {
            lock.unlock();
        }
        if (orderId==null) return Result.fail("一人一单");
        return Result.ok(orderId);
    }

    /**
     * @Description: 一人一单,分布式锁
     * @Param:  * @param voucherId
     * @return: com.hmdp.dto.Result
     * @Author: Feng
     * @Date:2023/03/09 11:01
     */
    private Result ofoWithRedislock(Long voucherId) {
        //判断优惠券状态
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        if(voucher==null) return Result.fail("该优惠券不存在");
        LocalDateTime now = LocalDateTime.now();
        if (voucher.getBeginTime().isAfter(now)) return Result.fail("优惠券还没开卖");
        if (voucher.getEndTime().isBefore(now)) return Result.fail("优惠券已结束");
        if (voucher.getStock()==0) return Result.fail("优惠券已经卖完");


        //使用互斥锁解决一人一单d
        Long orderId = null;
        Long userId = UserHolder.getUser().getId();
        System.out.println(1);
        //获取互斥锁
        RedisSimpleLock redisSimpleLock = new RedisSimpleLock("order:" , stringRedisTemplate);
        boolean isLock = redisSimpleLock.tryLock(userId.toString(), 1000L);
        try {
            if(isLock){
                IVoucherOrderService voucherOrderServiceProxy = (IVoucherOrderService)AopContext.currentProxy();
                orderId = voucherOrderServiceProxy.createOrder(voucherId);
            }
        } finally {
            redisSimpleLock.releaseLock(userId.toString());
        }
        if (orderId==null) return Result.fail("一人一单");
        return Result.ok(orderId);
    }



    /**
     * @Description: 一人一单
     * @Param:  * @param voucherId
     * @return: com.hmdp.dto.Result
     * @Author: Feng
     * @Date:2023/03/09 11:01
     */
    private Result ofo(Long voucherId) {
        //判断优惠券状态
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        if(voucher==null) return Result.fail("该优惠券不存在");
        LocalDateTime now = LocalDateTime.now();
        if (voucher.getBeginTime().isAfter(now)) return Result.fail("优惠券还没开卖");
        if (voucher.getEndTime().isBefore(now)) return Result.fail("优惠券已结束");
        if (voucher.getStock()==0) return Result.fail("优惠券已经卖完");

        //使用互斥锁解决一人一单
        Long orderId = null;
        synchronized (UserHolder.getUser().getId().toString().intern()){
            IVoucherOrderService voucherOrderServiceProxy = (IVoucherOrderService)AopContext.currentProxy();
            orderId = voucherOrderServiceProxy.createOrder(voucherId);
        }
        if (orderId==null) return Result.fail("一人一单");
        return Result.ok(orderId);
    }

    @Transactional
    //方法执行完事务才算提交
    public Long createOrder(Long voucherId) {
        Integer count = query().eq("voucher_id", voucherId).eq("user_id", UserHolder.getUser().getId()).count();
        if(count!=0) return null;
        //解决超卖,下单的时候再进行判断
        Boolean upd = seckillVoucherService.update().gt("stock",0).eq("voucher_id",voucherId).setSql(" stock = stock-1 ").update();
        if(!upd) return null;

        //插入订单
        VoucherOrder voucherOrder = new VoucherOrder();
        Long orderId = idWorker.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);
        return orderId;
    }


    /**
     * @Description: 解决超卖
     * @Param:  * @param voucherId
     * @return: com.hmdp.dto.Result
     * @Author: Feng
     * @Date:2023/03/09 11:01
     */
    private Result oversold(Long voucherId) {
        //判断优惠券状态
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        if(voucher==null) return Result.fail("该优惠券不存在");
        LocalDateTime now = LocalDateTime.now();
        if (voucher.getBeginTime().isAfter(now)) return Result.fail("优惠券还没开卖");
        if (voucher.getEndTime().isBefore(now)) return Result.fail("优惠券已结束");
        if (voucher.getStock()==0) return Result.fail("优惠券已经卖完");
        //解决超卖,下单的时候再进行判断
//        直接使用setSql
//        要使用seckillVoucher的方法
//        商品不足给友好提示
//        最后要加.update()
        Boolean upd = seckillVoucherService.update().gt("stock",0).eq("voucher_id",voucherId).setSql(" stock = stock-1 ").update();
        if(!upd) return Result.fail("商品不足");

        //插入订单
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(idWorker.nextId("order"));
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);
        return Result.ok();
    }
}
